package com.rpframework.module.common.bottom.api.baidu.com;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rpframework.core.json.FailException;
import com.rpframework.module.common.bottom.entity.po.Geography;
import com.rpframework.utils.OkHttpUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;

import static com.rpframework.module.common.bottom.api.baidu.com.Config.AK;


/**
 * 地图接口
 * Created by jump on 2016/8/29.
 */
public class Map {
    private static final String POSITION_URL = "/geocoder/v2/";

    /**
     * http://api.map.baidu.com/geocoder/v2/?ak=L8rtMV1Gbx2VGPBir4NkOlV4iZyOv56O&location=30.548397,104.04701&output=json&pois=1
     * 根据经纬度获取详细信息
     *
     * @param geography 经纬度
     * @return 信息
     */
    public static JsonMap getPosition(Geography geography) {
        Geography.baseValidate(geography);
        java.util.Map<String, Object> map = new LinkedHashMap<>();
        String address = geography.getAddress();
        if (!StringUtils.isBlank(address)) {
            map.put("address", address);
        } else {
            map.put("location", geography.getLatitude() + "," + geography.getLongitude());
        }
        map.put("output", "json");
        map.put("pois", 1);
        map.put("ak", AK);
        map.put("sn", SnCal.getSn(map, POSITION_URL));
        String post = OkHttpUtil.get(Config.HOST_MAP + POSITION_URL, map);
        Gson gson = new Gson();
        java.lang.reflect.Type type = new TypeToken<Json<JsonMap>>() {
        }.getType();
        Json<JsonMap> json = gson.fromJson(post, type);
        if (!json.getStatus().equals(0)) {
            String message = json.getMessage();
            if(StringUtils.isBlank(message)) message = json.getMsg();
            throw new FailException("MAP:" + message);
        }
        return json.getResult();
    }
}
